import Event from '../contorl/src/event/index'
import Taro from '@tarojs/taro'
import { Provider } from 'react-redux';

import './index.scss'

import { Body } from '../../componets/public'
import { Canvas } from '@tarojs/components'
import { useEffect, Component } from 'react';
import { createdGame, closeMusic } from '../contorl/src/main'
import { setCtx, setCanvas } from '../contorl/ctx/index'
import { getStaticState } from '../../state/static-store'
import { loadingImage } from './contorl'
import { Over } from './over';
import { StartButton } from './start-button'
import { Tips } from './tips'
import { store } from '../store'

const IndexPage = () => {
  const getCxt = (name = 'canvas') => {
    return new Promise((resolve, reject) => {
      try {
        const query = Taro.createSelectorQuery();
        query.select(name).fields({ node: true, size: true }).exec((res) => {
          
          const myCanvas = res[0].node;
          const myCtx = myCanvas.getContext('2d');
          const { devicePixelRatio } = getStaticState('systemInfo')
          myCanvas.width = res[0].width * devicePixelRatio;
          myCanvas.height = res[0].height * devicePixelRatio;
          myCtx.scale(devicePixelRatio, devicePixelRatio);
          resolve({ myCtx, myCanvas })
        })
      } catch (error) {
        reject(error)
      }

    })
  }
  const start = async (fn) => {
    setTimeout(async () => {
      const param = await getCxt('#game-id')
      fn(param)
    }, 0)
  }
  useEffect(() => {
    start(({ myCtx, myCanvas }) => {
      loadingImage(myCanvas)
      setCtx(myCtx)
      setCanvas(myCanvas)
      createdGame(myCtx)
    })
    return () => {
      closeMusic()
    }
  })
  const onTouchStart = (e) => {
    Event.emit('touchstart', e)
  }
  const onTouchEnd = (e) => {
    Event.emit('touchend', e)
  }
  const onTouchMove = (e) => {
    Event.emit('touchmove', e)
  }
  const { screenHeight: SCREEN_HRIGHT, screenWidth: SCREEN_WIDTH } = getStaticState('systemInfo');
  return <Body isNav={true}
              isNavSeat={false}
              navText={''}
              bodyClassName='nm-pages-index'>
    <Canvas className='canvas'
            type='2d'
            id="game-id"
            canvasId='game-id'
            onTouchStart={(e) => onTouchStart(e)}
            onTouchEnd={(e) => onTouchEnd(e)}
            onTouchMove={(e) => onTouchMove(e)}
            style={{
              width: `${SCREEN_WIDTH}px`,
              height: `${SCREEN_HRIGHT}px`
            }}/>
    <Over></Over>
    <StartButton></StartButton>
    <Tips></Tips>
  </Body>
}
export default class Index extends Component {
  onShareAppMessage (share) {
    if (share.from === 'button') {
      // 来自页面内转发按钮
      console.log(share.target)
    }
    return {
      title: '一起接金币'
    }
  }
  onShareTimeline() {
    return {
      title: '一起接金币',
    }
  }
  render() {
    return (<Provider store={store}>
      <IndexPage/>
    </Provider>)
  }
}